<template>
  <div class="list" ref="top">
    <van-pull-refresh
      v-model="isRefreshLoading"
      @refresh="onRefresh"
      :success-duration="1000"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="啥都没有咯"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <article-item
          v-for="(article, index) in list"
          :key="index"
          :article="article"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/articles";
import articleItem from "./article-item.vue";

export default {
  name: "ArticleList",
  components: {
    articleItem,
  },
  data() {
    return {
      list: [],
      isRefreshLoading: false,
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
    };
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  mounted() {
    this.$refs.top.addEventListener(
      "scroll",
      function () {
        // console.log(this.top);
        this.setAttribute("top", this.top);
        // console.log(top);
      },
      500
    );
  },
  // activated() {
  //   const Top = this.$refs.List.getAttribute("top");
  //   this.$refs.List.Top = Top;
  //   console.log(top);
  // },

  methods: {
    async onLoad() {
      try {
        // 异步更新数据
        const res = await getArticles({
          channel_id: this.channel.id,
          // 时间戳设置，第一次传输时间戳，值如果为null，则传入当前最新的时间Date.now
          timestamp: this.timestamp || Date.now(),
          // 包含头部传1，不包含传0
          with_top: 1,
        });
        this.list.push(...res.data.results);
        this.loading = false;
        if (res.data.results.length > 0) {
          // 如果还有数据,则将时间戳赋值给timestamp
          this.timestamp = res.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (error) {
        this.loading = false;
        this.error = true;
      }
    },
    onRefresh() {
      this.loading = true;
      this.list = [];
      this.finished = false;
      this.timestamp = null;
      this.error = false;
      this.onLoad();
      this.isRefreshLoading = false;
    },
  },
};
</script>

<style lang="less" scoped>
.list {
  height: calc(100vh - 188px);
  margin-top: 88px;
  overflow-y: auto;
}

// .list {
//   overflow: auto;
//   margin-top: 88px;
//   left: 0;
//   right: 0;
//   top: 88px;
//   bottom: 100px;
// }
</style>